var createError = require('http-errors');
var express = require('express');
var path = require('path');
// 用于登录验证
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// 导入路由文件
var indexRouter = require('./routes/index');
var apiRouter = require('./routes/api');
var app_login_Router = require('./routes/login');


var app = express();
//设置允许跨域访问该服务.


app.all('*', function (req, res, next) {
    //设为指定的域
    res.header('Access-Control-Allow-Origin', "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header('Access-Control-Allow-Credentials', true);
    res.header("X-Powered-By", ' 3.2.1');
    next();
});



require('./utils/db') //链接数据库mongoose
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade'); //定义渲染模板

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 2、如果你希望所有通过 express.static 访问的文件都存放在一个“虚拟
// （virtual）”目 录（即目录根本不存在）
// 下面，可以通过为静态资源目录指定一个挂载路径的方式来实现，
//  如下所示： app.use('/static', express.static('public'));


// 路由安装 
app.use('/', indexRouter);
app.use('/api', apiRouter);
app.use('/app', app_login_Router)




// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('error');
});



app.listen(5000, () => {
    console.log('启动成功 5000');
});



module.exports = app;